package com.itheima.mq;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import com.itheima.utils.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author Guanxing
 * @date 2021/10/9
 */
@Component
public class RecommendMovementTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/5 * * * * *")
    public void run() {
        System.out.println("开启动态推荐,正在读取redis数据加载到mongo中...");
        //读取redis数据
        Set<String> keys = stringRedisTemplate.keys(ConstantUtil.QUANZI + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            //遍历key
            for (String key : keys) {
                //读取value
                String value = stringRedisTemplate.opsForValue().get(key);

                //切割数据
                String[] pids = value.split(",");

                if (pids != null) {
                    //获得用户id
                    Long userId = Long.valueOf(key.replaceAll(ConstantUtil.QUANZI, ""));
                    //删除历史推荐数据
                    Query removeQuery = new Query(
                            Criteria.where("userId").is(userId)
                    );
                    mongoTemplate.remove(removeQuery, RecommendMovement.class);

                    //循环添加新数据
                    for (String pid : pids) {
                        Query query = new Query(
                                Criteria.where("pid").is(Long.valueOf(pid))
                        );
                        Movement movement = mongoTemplate.findOne(query, Movement.class);
                        //将movement转换成recommend_movement
                        RecommendMovement recommendMovement = new RecommendMovement();
                        recommendMovement.setCreated(System.currentTimeMillis());
                        recommendMovement.setUserId(userId);
                        recommendMovement.setPid(Long.valueOf(pid));
                        recommendMovement.setPublishId(movement.getId());
                        //有坑, 大数据这边推送的数据的时候 少传一个分值 (后续跟大数据沟通)
                        recommendMovement.setScore(RandomUtil.randomDouble(60,99)); //暂时只能自己随机

                        mongoTemplate.save(recommendMovement);
                    }


                }
            }
        }
    }
}
